<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>发起【{{ processName }}】流程</span>
      </div>
      <el-col :span="24">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="申请人" prop="userName">
                <el-input v-model="form.userName" show-word-limit :maxlength="100" placeholder="请输入申请人名称"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="文件名称" prop="fileName">
                <el-input v-model="form.fileName" placeholder="请输入文件名称" show-word-limit :maxlength="100"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文件份数" prop="fileShare">
                <el-input-number v-model="form.fileShare" :min="1" size="small"></el-input-number>
                /份
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="文件类型" prop="fileType" style="width: 50%;">
                <el-select v-model="form.fileType" placeholder="请选择文件类型" style="width: 100%;">
                  <el-option v-for="dict in dict.type.work_sign_type" :key="dict.value" :label="dict.label"
                             :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签署日期" prop="signDate" style="width: 50%;">
                <el-date-picker v-model="form.signDate"
                                clearable
                                placeholder="请选择签署日期"
                                style="width: 100%;"
                                type="date"
                                value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="主文件" prop="masterFile">
                <file-upload v-model="form.masterFile" :fileSize="50"
                             :fileType="['pdf','docx','doc','xls','xlsx','png']" :limit="1"
                             :uploadFileUrl="uploadFileUrl" @change="masterFileChange"
                             @delete="fileDelete"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="附件">
                <file-upload v-model="form.files" :fileSize="50"
                             :fileType="['pdf','docx','doc','xls','xlsx','png']" :limit="5"
                             :uploadFileUrl="uploadFileUrl" @change="fileChange"
                             @delete="fileDelete"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="事由" prop="subject">
                <el-input v-model="form.subject" :rows="4" placeholder="请输入事由" type="textarea" show-word-limit
                          :maxlength="255"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" show-word-limit :maxlength="255" :rows="4" placeholder="请输入备注"
                          type="textarea"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button type="primary"
                       v-if="form.schedule === 'terminated' || form.schedule === 'canceled' || form.schedule === 'unapproved'"
                       @click="submitForm(1)">提 交
            </el-button>
            <el-button type="primary" @click="submitForm(0)">保 存</el-button>
            <el-button @click="cancel">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-card>

    <el-collapse v-if="!disable">
      <el-collapse-item title="流程图">
        <el-card class="box-card">
          <process-viewer :key="`designer-${definitionId}`" :xml="xmlData" :style="{height: '700px'}"/>
        </el-card>
      </el-collapse-item>
    </el-collapse>

  </div>
</template>

<script>
import {getBpmnXml} from '@/api/workflow/process'
import Parser from '@/utils/generator/parser'
import ProcessViewer from '@/components/ProcessViewer'
import {getSign, updateSign} from "@/api/work/sign";

export default {
  name: 'UpdateSign',
  dicts: ['work_sign_type'],
  components: {
    Parser,
    ProcessViewer
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/common/pdf/upload',


      definitionId: null,
      disable: false,
      processName: null,
      xmlData: null,

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        masterFile: [
          {required: true, message: '主文件不能为空', trigger: 'blur'}
        ],
        userName: [
          {required: true, message: '申请人不能为空', trigger: 'blur'}
        ],
        fileName: [
          {required: true, message: '文件名称不能为空', trigger: 'blur'}
        ],
        signDate: [
          {required: true, message: '签署日期不能为空', trigger: 'blur'}
        ],
        subject: [
          {required: true, message: '签署事由不能为空', trigger: 'blur'}
        ]
      },
      userData: {}
    }
  },
  created() {
    this.definitionId = this.$route.query && this.$route.query.definitionId;
    this.processName = this.$route.query && this.$route.query.processName;
    let businessId = this.$route.query && this.$route.query.businessId;
    if (!businessId) {
      this.$message.error('signId不能为空');
      return
    }

    if (!this.definitionId) {
      this.$message.error('definitionId不能为空');
      return
    }

    if (!this.definitionId) {
      this.$message.error('processName不能为空');
      return
    }

    this.reset();

    getSign(businessId).then(res => {
      res.data.masterFile = res.data.signFileList.filter(item => {
        return item.type === '1'
      }).map(item => item.fileUrl).join(',')
      res.data.files = res.data.signFileList.filter(item => {
        return item.type === '2'
      }).map(item => item.fileUrl).join(',')
      this.form = res.data
      this.initData();
    })
  },
  methods: {
    fileDelete(index) {
      this.form.signFileList.splice(index, 1)
    },
    masterFileChange(e) {
      this.form.signFileList.push({
        page: e.pages,
        fileUrl: e.fileName,
        width: JSON.stringify(e.width),
        height: JSON.stringify(e.height),
        fileName: e.originalFilename,
        type: '1'
      })
    },
    fileChange(e) {
      this.form.signFileList.push({
        page: e.pages,
        fileUrl: e.fileName,
        width: JSON.stringify(e.width),
        height: JSON.stringify(e.height),
        fileName: e.originalFilename,
        type: '2'
      })
    },

    initData() {
      // 发送请求，获取xml
      getBpmnXml(this.definitionId).then(response => {
        this.xmlData = response.data
      })
    },
    // 表单重置
    reset() {
      this.form = {
        signId: null,
        userId: null,
        deptId: null,
        userName: null,
        deptName: null,
        definitionId: null,
        processName: null,
        files: null,
        masterFile: null,
        fileName: null,
        fileShare: null,
        fileType: '1',
        subject: null,
        signFileList: [],
        remark: null,
        schedule: null,
        signDate: new Date(),
        delFlag: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      const obj = {path: "/work/sign"};
      this.$tab.closeOpenPage(obj);
    },
    /** 提交按钮 */
    submitForm(index) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.disable) {
            return
          }
          if (!(this.form.schedule === "completed")) {
            if (index === 0) {
              this.form.schedule = 'unapproved'
            } else {
              this.form.schedule = 'running'
            }
          }
          this.form.definitionId = this.definitionId
          this.form.processName = this.processName
          updateSign(this.form).then(response => {
            this.$modal.msgSuccess(`${this.form.schedule === 'unapproved' ? '保存' : '提交'}成功`)
            this.cancel()
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.form-conf {
  margin: 15px auto;
  width: 80%;
  padding: 15px;
}
</style>
